package com.cangxuan.manage.context;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class ApplicationContextHolder implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    /**
     * 根据名称获取bean
     * @param beanName
     * @return
     * @param <T>
     */
    public static <T>T getBean(String beanName) {
        return (T) applicationContext.getBean(beanName);
    }

    /**
     * 根据类型获取bean
     * @param beanType
     * @return
     * @param <T>
     */
    public static <T>T getBean(Class<T> beanType) {
        return applicationContext.getBean(beanType);
    }

}
